package com.hwd.gmall.order.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 订单微服务发起远程feign调用的拦截器
 *
 * @author 黄伟东/Victor
 * @date 2022/5/7 23:16
 */
@Component
public class OrderInterceptor implements RequestInterceptor {

    /**
     * 生效的时机: 本微服务的所有feign调用发起前
     * @param requestTemplate Http请求模板对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取上一个线程的request对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            // 获取request对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 获取request里的全部头消息
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                // 获取每个请求头的中参数的名字
                String name = headerNames.nextElement();
                // 获取请求头中的值
                String value = request.getHeader(name);
                // 放到requestTemplate对象的请求头中
                requestTemplate.header(name, value);
            }
        }

    }
}
